/*
 * @Description: In User Settings Edit
 * @Author: your name
 * @Date: 2019-10-02 16:32:12
 * @LastEditTime: 2019-10-05 12:29:06
 * @LastEditors: Please set LastEditors
 */
import axios from 'axios'
import {Message,Loading} from 'element-ui'
import router from './router'

let loading        //定义loading变量
function startLoading(){
    loading = Loading.service({
        lock:true,
        text:'拼命加载中~',
        background:'rgba(0,0,0,0.7)'
    })
}

function endLoading(){
    loading.close()
}

// 请求拦截
axios.interceptors.request.use(config=>{
    // 加载动画
    startLoading()

    if(localStorage.eleToken){
        config.headers.Authorization = localStorage.eleToken

    }else{

    }

    return config
},err=>{
    

    return Promise.reject(err)
})


// 响应拦截

axios.interceptors.response.use(response=>{
    // 结束加载动画
    endLoading()
    return response
},err=>{
    console.log(err)
    endLoading()
    Message.error(err.response.data)
    // 获取错误状态码
    const {status} = err.response
    if(status == 401){
        Message.error('token失效，请重新登录')
        localStorage.removeItem('eleToken')
        // 跳转到登录页面
        router.push('/login')
    }
    return Promise.reject(err)
})

export default axios